from app.extensions import db
from app.models.model_mixin import BaseMixin
from app.models.article import Article
from app.helpers import cache


# 单位
class Companys(db.Model, BaseMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), index=True)
    pid = db.Column(db.Integer, db.ForeignKey('companys.id'), default=None)

    users = db.relationship('User', back_populates='company')
    children = db.relationship('Companys', backref=db.backref('parent', remote_side=[id]))

    # 获取录用文章
    def get_hired_count(self):
        count = cache.get('c_hired_count_{}'.format(self.id))
        if count is None:
            count = Article.query.filter(Article.uid.in_([u.id for u in self.users]), Article.rid != None, Article.status == 9).count()
            cache.set('c_hired_count_{}'.format(self.id), count, timeout=60)
        return count

    # 获取未录用文章
    def get_not_hired_count(self):
        count = cache.get('c_not_hired_count_{}'.format(self.id))
        if count is None:
            count = Article.query.filter(Article.uid.in_([u.id for u in self.users]), Article.rid == None, Article.status == 9).count()
            cache.set('c_not_hired_count_{}'.format(self.id), count, timeout=60)
        return count

    # 获取报送积分
    def get_hired_integral(self):
        return self.get_hired_count() * 2 + self.get_not_hired_count() * 1

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'pid': 0 if self.pid is None else self.pid,
            'hired_count': self.get_hired_count(),
            'not_hired_count': self.get_not_hired_count(),
            'hired_integral': self.get_hired_integral()
        }

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
